package com.zy.oauth.dto;


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zy.common.core.constant.Constants;
import com.zy.common.core.enums.ErrorEnums;
import com.zy.common.core.exception.BizException;
import com.zy.oauth.entity.Account;
import com.zy.oauth.entity.RolePermission;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@Slf4j
@JsonIgnoreProperties({"enabled", "accountNonExpired", "accountNonLocked", "credentialsNonExpired", "authorities"})
public class AccountDto extends Account implements UserDetails, CredentialsContainer {

    private String username;
    private String password;
    private String token;
    private Set<String> roles;
    private List<RolePermissionDto> permissions;

    @Override
    public void eraseCredentials() {

    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<String> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(permissions)) {
            throw new BizException(ErrorEnums.UNAUTHORIZED);
        }
        if (!CollectionUtils.isEmpty(permissions)) {
            list = permissions.stream().map(e -> {
                return e.getPath();
            }).collect(Collectors.toList());
        }
        return AuthorityUtils.createAuthorityList(String.join(",", list));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
